package com.atguigu.self.gulimall.product.service.impl;

import com.atguigu.self.common.to.SkuReductionTO;
import com.atguigu.self.common.to.SpuBoundTO;
import com.atguigu.self.common.utils.R;
import com.atguigu.self.gulimall.product.entity.*;
import com.atguigu.self.gulimall.product.feign.CouponFeignService;
import com.atguigu.self.gulimall.product.service.*;
import com.atguigu.self.gulimall.product.vo.Bounds;
import com.atguigu.self.gulimall.product.vo.Images;
import com.atguigu.self.gulimall.product.vo.Skus;
import com.atguigu.self.gulimall.product.vo.SpuSaveVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.self.common.utils.PageUtils;
import com.atguigu.self.common.utils.Query;

import com.atguigu.self.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.jsf.el.WebApplicationContextFacesELResolver;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService saveSkuInfo;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * TODO 处理失败信息 -> 当插库失败，事务回滚时该怎么处理， 以及服务不稳定导致数据处理失败时如何处理 都在高级篇
     *
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、 保存spu基本信息； pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);

        //2、保存spu的描述图片；pms_spu_info_desc
        List<String> decript = vo.getDecript();
        String imageDecript = String.join(",", decript);
        SpuInfoDescEntity infoDescEntity = new SpuInfoDescEntity();
        infoDescEntity.setSpuId(infoEntity.getId());
        infoDescEntity.setDecript(imageDecript);
        spuInfoDescService.saveSpuInfoDesc(infoDescEntity);

        //3、保存spu的图片集； pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveSpuImages(infoEntity.getId(), images);

        //4、保存spu的规格参数； pms_product_attr_value
        productAttrValueService.saveProductAttrValue(infoEntity.getId(), vo.getBaseAttrs());

        //5、保存spu积分信息；gulimail_sms -> spu积分表sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTO spuBoundTO = new SpuBoundTO();
        BeanUtils.copyProperties(bounds, spuBoundTO);
        spuBoundTO.setSpuId(infoEntity.getId());
        R spuBounds = couponFeignService.saveSpuBounds(spuBoundTO);
        if (spuBounds.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        //6、保存spu对应的所有sku信息；
        // 6.1、保存sku基本信息; pms_sku_info
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {

            skus.forEach(sku -> {
                // 获取sku默认图片
                String defaultImage = "";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImage = image.getImgUrl();
                    }
                }
                // 封装sku信息，并入库保存sku信息
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                saveSkuInfo.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId(); // 获取sku主键id

                // 6.2、保存sku图片信息
                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(skuImagesEntity -> StringUtils.isNotBlank(skuImagesEntity.getImgUrl()))
                        .collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);


                // 6.3、保存sku销售属性关联关系(表)
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = sku.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);

                // 6.4、保存sku优惠、满减等信息；gulimail_sms -> sku满减打折sms_sku_ladder、sms_sku_full_reduction
                // 会员等级价格打折 sms_member_price
                SkuReductionTO skuReductionTO = new SkuReductionTO();
                BeanUtils.copyProperties(sku, skuReductionTO);
                skuReductionTO.setSkuId(skuId);
                R skuReduction = couponFeignService.saveSkuReduction(skuReductionTO);
                if (skuReduction.getCode() != 0) {
                    log.error("远程保存sku优惠信息失败");
                }

            });

        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {

        this.save(infoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq("id", key).or().like("spu_name", key);
            });
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);

        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotBlank(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }


}